package ru.spb.osll.myfit.fixtures.log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.PropertyResourceBundle;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

public class MyFitLogger {

  private static LinkedList<FileAppender> appendersToClose = new LinkedList<FileAppender>();

  private static String LOG_CONFIG_FILE_NAME = "logconfig.properties";

  public static Logger getLogger(Class< ? > clazz) {
    Logger logger = Logger.getLogger(MyFitLogger.class);

    ClassLoader classLoader = clazz.getClassLoader();
    URL[] ur = ((URLClassLoader) classLoader).getURLs();
    File logConfigFile = null;

    for (URL url : ur) {
      File file = new File(url.getFile());
      if (file.isDirectory()) {
        for (String fileName : file.list()) {
          if (fileName.equals(LOG_CONFIG_FILE_NAME)) {
            logConfigFile = new File(file, fileName);
            break;
          }
        }
      }
    }

    if (logConfigFile == null) {
      return Logger.getLogger(clazz);
    }

    FileInputStream in = null;
    try {

      in = new FileInputStream(logConfigFile);
      PropertyResourceBundle bundle = new PropertyResourceBundle(in);
      String filename = bundle.getString("logFile");
      String loggerName = bundle.getString("loggerName");
      in.close();

      Logger LOG = createLoger(loggerName, filename);
      return LOG;

    } catch (Exception ex) {
      logger.warn("can not find bundle", ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e1) {

        }
      }
    }
    return Logger.getLogger(clazz);
  }

  @SuppressWarnings("rawtypes")
  private static Logger createLoger(String loggerName, String logFile) {
    Logger LOG = Logger.getLogger(loggerName);
    Enumeration allAppenders = LOG.getAllAppenders();
    if (!allAppenders.hasMoreElements()) {
      FileAppender appender;
      try {

        appender = new FileAppender(new PatternLayout(
            "%d{ABSOLUTE} %5p  %C{1} - %m%n"), logFile);
        LOG.addAppender(appender);
        appendersToClose.add(appender);
      } catch (Exception e) {
      }
      LOG.setAdditivity(false);
      LOG.setLevel(Level.INFO);
    }
    return LOG;
  }

  public static void closeAppenders() {
    for (FileAppender appender : appendersToClose) {
      appender.close();
    }
  }
}
